package com.sjgs.gis.repository;

import com.sjgs.gis.domain.Chunk;
import com.sjgs.gis.domain.DataFile;
import org.springframework.data.mongodb.repository.Query;
import org.springframework.data.mongodb.repository.ReactiveMongoRepository;
//import org.springframework.data.r2dbc.repository.Query;
//import org.springframework.data.r2dbc.repository.R2dbcRepository;
//import org.springframework.data.repository.reactive.ReactiveCrudRepository;
import org.springframework.data.r2dbc.repository.R2dbcRepository;
import org.springframework.stereotype.Repository;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

@Repository
public interface ChunkRepository extends R2dbcRepository<Chunk, Long> {
    //块级续传
    Mono<Chunk> findByFkeyAndIndexAndHashAndStatus(String fkey, Long index, String hash, Integer status);
    //片对比
    Flux<Chunk> findAllByFkeyEndsWith(String fname);
    //找出某状态的所有块
    Flux<Chunk> findAllByFkeyAndStatus(String fkey, Integer status);

    Flux<Chunk> findAllByFkeyAndStatusAndChunkAddrIsNot(String fkey, Integer status, String chunkAddr);

    Flux<Chunk> findAllByFkeyAndIndex(String fkey, Long index);

    Mono<Long> countByFkeyAndStatus(String fkey, Integer status);

    Mono<Void> deleteAllByFkey(String fkey);

    //块区间定位
    @Query("with " +
            "finished_chunk as (select * from chunk where fkey = :fkey and status = :status) " +
            "select chunk.* from finished_chunk t where " +
            "(chunk_start <= :start and chunk_end >= :start) " +
            "or " +
            "(chunk_start > :start and chunk_end < :end) " +
            "or " +
            "(chunk_start <= :end and chunk_end >= :end) order by index asc")
    Flux<Chunk> findAllByFkeyAndStatusAndStartAndAndEnd(String fkey, Integer status, Long start, Long end);
}
